<template>
  <div class="app-container">
    <el-form inline label-width="140px">
      <el-form-item label="状态：" prop="status">
        <el-select
          v-model="status"
          clearable
          placeholder="请选择状态"
          @change="selectStatus"
        >
          <el-option
            v-for="(key, val) in statusMap"
            :key="key"
            :label="key"
            :value="val"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="内部订单编号：" prop="innerCode" width="160px">
        <el-input v-model.trim="innerCode" clearable @clear="selected" />
      </el-form-item>
      <div class="establish">
        <el-button
          type="primary"
          size="small"
          @click="selected"
        >查询
        </el-button
        >
      </div>
    </el-form>

    <div class="establish">
      <el-button
        v-if="hasApplyRole"
        type="primary"
        size="small"
        @click="dialogFileUpload.show = true"
      >导入
      </el-button
      >
      <el-button
        v-if="hasApplyRole"
        type="primary"
        size="small"
        @click="purchaseApply.dialogshow = true"
      >采购申请
      </el-button
      >
    </div>

    <el-table
      :data="list"
      :header-row-style="{
        'background-color': '#E6E6E6',
        'font-weight': 'bold',
        color: '#333'
      }"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      border
      height="650"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
    >
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="innerCode"
        label="内部订单编号"
        width="160px"
      /><el-table-column
        show-overflow-tooltip
        align="center"
        prop="chartNo"
        label="图号"
        width="180px"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="materialName"
        label="物料名称"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="materialType"
        label="物料类型"
      >
        <template slot-scope="scope">
          {{ materialTypeMap[scope.row.materialType] || "--" }}
        </template>
      </el-table-column>

      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="materialType"
        label="采购类型"
      >
        <template slot-scope="scope">
          {{
            scope.row.materialType == 2
              ? purchaseTypeMap[scope.row.purchaseType]
              : "--"
          }}
        </template>
      </el-table-column>

      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="brand"
        label="品牌"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="specifications"
        label="规格"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="applyAmount"
        label="申请数量"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        width="120"
        prop="demandTime"
        label="需求时间"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        width="120"
        prop="purchaseTime"
        label="采购时间"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        width="120"
        prop="supplierName"
        label="采购商家"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="unit"
        label="单位"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="purchaseAmount"
        label="购买数量"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="qualityAmount"
        label="品检合格数"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="unqualityAmount"
        label="品检不合格数"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="arriveAmount"
        label="到货数"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="realAmount"
        label="入库数"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="status"
        width="120"
        label="状态"
      >
        <template slot-scope="scope">
          {{ statusMap[scope.row.status] }}
        </template>
      </el-table-column>
      <!-- <el-table-column show-overflow-tooltip align="center" prop="deliveryTime" label="状态"/>
        <el-table-column show-overflow-tooltip align="center" prop="creator" label="状态" /> -->
      <el-table-column
        v-if="hasSeePriceRole"
        show-overflow-tooltip
        align="center"
        prop="price"
        label="价格"
      />
      <el-table-column
        v-if="hasSeePriceRole"
        show-overflow-tooltip
        align="center"
        prop="totalPrice"
        label="总价格"
      />
      <!-- <el-table-column
        show-overflow-tooltip
        align="center"
        prop="operator"
        label="操作者"
      >
        <template slot-scope="scope">
          {{
            scope.row.operator &&
            scope.row.operator.indexOf("{") > -1 &&
            scope.row.operator.indexOf("}") > -1 &&
            scope.row.operator.indexOf(",") > -1
              ? JSON.parse(scope.row.operator).fullName
              : scope.row.operator
          }}
        </template>
      </el-table-column> -->
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="comment"
        label="备注"
      />

      <el-table-column fixed="right" width="100" label="操作">
        <template slot-scope="scope">
          <!--    如果是生产主管，则展示状态为0的需要审核      -->
          <!-- <el-button
            v-if="(isProductionStaff || isAdmin) && scope.row.status == 0"
            type="text"
            size="mini"
            @click="auditAction(scope.row)"
            >审核</el-button
          > -->
          <!-- 刀具直接入库，物料需要品检通过才可以入库 -->
          <el-button
            v-if="
              (isPlatestorage || isAdmin) &&
                isFromPlatestorage &&
                ((scope.row.purchaseType == 1 && scope.row.status == 2) ||
                (scope.row.purchaseType == 2 && scope.row.status == 3) ||
                (scope.row.purchaseType == 2 && scope.row.status == 4))
            "
            type="text"
            size="mini"
            @click="storageAction(scope.row)"
          >入库
          </el-button
          >
          <!-- (scope.row.purchaseType == 2 && scope.row.status == 4) || -->
          <el-button
            v-if="
              isPurchase &&
                isFromPurchase &&
                (scope.row.status == 1 ||
                (scope.row.purchaseType == 1 &&
                scope.row.status == 5 &&
                scope.row.purchaseAmount < scope.row.applyAmount) ||
                (scope.row.purchaseType == 2 &&
                scope.row.status == 4 &&
                scope.row.qualityAmount < scope.row.applyAmount))
            "
            type="text"
            size="mini"
            @click="purchaseUpdateAction(scope.row)"
          >采购
          </el-button
          >
          <el-button
            v-if="scope.row.status == 1 && isFromPurchase||(isAdmin&&isPurchaser) "
            type="text"
            size="mini"
            @click="applyTurnDown(scope.row)"
          >
            驳回
          </el-button
          >
          <el-button
            v-if="
              (isProductionStaff || isAdmin) &&
                isFromManufacturing &&
                scope.row.status == 0
            "
            type="text"
            size="mini"
            @click="approvalAction(scope.row)"
          >
            审批
          </el-button>

          <el-button
            v-if="
              (isProductionStaff || isAdmin) &&
                isFromManufacturing &&
                scope.row.status == 0
            "
            type="text"
            size="mini"
            @click="turnDownAction(scope.row)"
          >
            驳回
          </el-button>

          <el-button
            v-if="
              (isResubmitAuth) &&
                isFromManufacturing &&
                scope.row.status == 7
            "
            type="text"
            size="mini"
            @click="resubmit(scope.row)"
          >
            编辑
          </el-button>

          <el-button
            v-if="
              isPurchase && (isPurchaser || isAdmin) && scope.row.status == 2
            "
            type="text"
            size="mini"
            @click="arrivalAction(scope.row)"
          >
            到货
          </el-button>
          <el-button
            v-if="
              isPurchase && (isAdmin) && scope.row.status === 11
            "
            type="text"
            size="mini"
            @click="managerApprovalMethod(scope.row)"
          >
            总经理审批
          </el-button>
          <el-button
            v-if="
              isPurchase && (isAdmin) && scope.row.status === 12
            "
            type="text"
            size="mini"
            @click="managerApprovalMethod(scope.row)"
          >
            董事长审批
          </el-button>
          <el-button
            v-if="scope.row.productId"
            type="text"
            size="mini"
            @click="seePaper(scope.row)"
          >查看图纸</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      style="padding: 30px 0; text-align: end"
      layout="total, prev, pager, next,jumper"
      @current-change="fetchData"
    />

    <!-- 物料入库 -->
    <el-dialog :visible.sync="storage.dialogshow" title="物料入库">
      <el-form
        ref="storageForm"
        :model="storage"
        :rules="storage.rules"
        label-width="110px"
        inline
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="物料名称">{{
              storage.row.materialName
            }}
            </el-form-item>
            <el-form-item label="品牌">{{ storage.row.brand }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图号">{{ storage.row.chartNo }}</el-form-item>
            <el-form-item label="规格">{{
              storage.row.specifications
            }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="主管人员名称" prop="manager">
          <select-user :name-val="storage.manager" @valChange="valChangeManager"/>
        </el-form-item>

        <el-form-item label="记账人员名称" prop="tallyer">
          <select-user :name-val="storage.tallyer" @valChange="valChangeTallyer"/>
        </el-form-item>

        <el-form-item label="经手人名称" prop="handlers">
          <select-user :name-val="storage.handlers" @valChange="valChangeHandlers"/>
        </el-form-item>

        <el-form-item label="仓库人员名称" prop="storager">
          <el-input
            v-model.trim="storage.storager"
            disabled
            placeholder="请输入仓库人员名称"
          />
        </el-form-item>

        <el-form-item label="入库数量" prop="amount">
          <el-input-number
            v-model="storage.applyAmount"
            :min="1"
            :max="storage.row.applyAmount"
            label="请输入入库数量"
          />
          {{ storage.row.unit }}
        </el-form-item>

        <el-form-item label="备注" prop="comment">
          <el-input
            :rows="2"
            v-model.trim="storage.comment"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="storage.loading"
          type="primary"
          @click="confirmStorage('form')"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>

    <!-- 采购申请 -->
    <el-dialog :visible.sync="purchaseApply.dialogshow" title="采购申请">
      <el-form
        ref="applyform"
        :model="purchaseApply.form"
        :rules="purchaseApply.rules"
        label-width="110px"
        inline
      >
        <el-form-item label="订单号" prop="orderCode">
          <el-input
            v-model.trim="purchaseApply.form.orderCode"
            placeholder="请输入订单号"
          />
        </el-form-item>
        <!--        <el-form-item label="内部单号" prop="innerCode">-->
        <!--          <el-input-->
        <!--            v-model.trim="purchaseApply.form.innerCode"-->
        <!--            placeholder="请输入内部单号"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item label="内部单号" prop="innerCode">
          <el-select
            v-model="purchaseApply.form.innerCode"
            :remote-method="remoteInnerCode"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词">
            <el-option
              v-for="item in innerCodeOptions"
              :key="item.id"
              :label="item.insideCode"
              :value="item.insideCode"/>
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="物料类型" prop="materialType">
              <el-radio-group v-model="purchaseApply.form.materialType">
                <el-radio :label="1" disabled>产品</el-radio>
                <el-radio :label="2">材料</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              v-if="purchaseApply.form.materialType == 2"
              label="采购类型"
              prop="purchaseType"
            >
              <el-radio-group v-model="purchaseApply.form.purchaseType">
                <el-radio :label="1">刀具</el-radio>
                <el-radio :label="2">物料</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="物料名称" prop="materialName">
          <el-input
            v-model.trim="purchaseApply.form.materialName"
            placeholder="请输入物料名称"
          />
        </el-form-item>
        <!--        <el-form-item label="图号" prop="chartNo">-->
        <!--          <el-input-->
        <!--            v-model.trim="purchaseApply.form.chartNo"-->
        <!--            placeholder="请输入图号"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item label="图号" prop="chartNo">
          <!--          <el-input-->
          <!--            v-model.trim="storageAdd.form.chartNo"-->
          <!--            placeholder="请输入图号"-->
          <!--          />-->
          <el-select
            v-model="purchaseApply.form.chartNo"
            :remote-method="remoteMaterialName"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词">
            <el-option
              v-for="item in materialNameOptions"
              :key="item.id"
              :label="item.picCode"
              :value="item.picCode"/>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input
            v-model.trim="purchaseApply.form.brand"
            placeholder="请输入品牌"
          />
        </el-form-item>
        <el-form-item label="规格型号" prop="specifications">
          <el-input
            v-model.trim="purchaseApply.form.specifications"
            placeholder="请输入规格型号"
          />
        </el-form-item>
        <el-form-item label="申请采购数量" prop="applyAmount">
          <el-input-number
            v-model="purchaseApply.form.applyAmount"
            :min="1"
            placeholder="请输入申请采购数量"
          />
        </el-form-item>
        <el-form-item label="需求时间" prop="demandTime">
          <el-date-picker
            :picker-options="pickerOptions"
            v-model="purchaseApply.form.demandTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input
            v-model.trim="purchaseApply.form.unit"
            placeholder="请输入单位"
          />
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input
            v-model.trim="purchaseApply.form.comment"
            :row="2"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="purchaseApply.loading"
          type="primary"
          @click="confirmPurchaseApply"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>

    <!-- 审核确认 -->
    <!-- <el-dialog :visible.sync="auditApply.dialogshow" title="审核确认">
      <el-form
        ref="auditApplyForm"
        :model="auditApply.form"
        :rules="auditApply.rules"
        label-width="140px"
      >
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="auditApply.loading"
          type="primary"
          @click="confirmAudit"
          >确 定</el-button
        >
      </div>
    </el-dialog> -->

    <!-- 采购确认 -->
    <el-dialog :visible.sync="purchaseUpdate.dialogshow" title="采购确认">
      <el-form
        ref="form"
        :model="purchaseUpdate.form"
        :rules="purchaseUpdate.rules"
        label-width="140px"
      >
        <el-form-item label="物料名称">
          {{ purchaseUpdate.row.materialName }}
        </el-form-item>

        <el-form-item label="本次申请数量">
          {{ purchaseUpdate.row.applyAmount }}
        </el-form-item>

        <el-form-item prop="purchaseAmount" label="本次采购数量">
          <el-input-number
            v-model="purchaseUpdate.form.purchaseAmount"
            :min="1"
            :max="
              purchaseUpdate.row.purchaseType == 1
                ? purchaseUpdate.row.applyAmount -
                  purchaseUpdate.row.purchaseAmount
                : purchaseUpdate.row.applyAmount -
                  purchaseUpdate.row.qualityAmount
            "
            placeholder="请输入申请采购数量"
          />
        </el-form-item>

        <el-form-item prop="purchaseTime" label="本次采购时间">
          <el-date-picker
            :picker-options="pickerOptions"
            v-model="purchaseUpdate.form.purchaseTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
          />
        </el-form-item>

        <el-form-item prop="price" label="单价">
          <el-input-number
            v-model="purchaseUpdate.form.price"
            :min="1"
            placeholder="请输入单价"
          />
        </el-form-item>

        <el-form-item label="采购商家" prop="supplierName">
          <el-input
            :rows="2"
            v-model.trim="purchaseUpdate.form.supplierName"
            type="input"
            placeholder="请输入采购商家"
          />
        </el-form-item>

        <el-form-item label="备注" prop="comment">
          <el-input
            :rows="2"
            v-model.trim="purchaseUpdate.form.comment"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="purchaseUpdate.loading"
          type="primary"
          @click="confirmPurchaseUpdateAction"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="approval.visible"
      title="审核提示"
      width="30%"
      @close="closeApprovalDialog"
    >
      <span>确定审核通过？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeApprovalDialog">取 消</el-button>
        <el-button
          :loading="approval.loading"
          type="primary"
          @click="confirmApproval"
        >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog :visible.sync="dialogFileUpload.show" title="导入" width="400px">
      <el-form>
        <el-form-item label="文件上传：">
          <template v-if="dialogFileUpload.fileName.length == 0">
            <el-upload
              :multiple="false"
              :before-upload="beforeUploadFile"
              action="#"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传excel文件
              </div>
            </el-upload>
          </template>

          <div v-else class="the-file">
            {{ dialogFileUpload.fileName }}
            <el-button
              type="danger"
              size="small"
              class="the-file-delete"
              icon="el-icon-delete"
              @click="removeFile"
            />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            :disabled="dialogFileUpload.disabled"
            :loading="dialogFileUpload.loading"
            type="primary"
            @click="confirmUpload"
          >确认上传
          </el-button
          >
          <el-button @click="closeUploadFileDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :visible.sync="arrival.show" title="到货确认" width="400px">
      <el-form
        ref="arrivalForm"
        :model="arrival.form"
        :rules="arrival.rules"
        label-width="140px"
      >
        <!-- <el-form-item label="供应商名称" prop="supplierName">
          <el-input
            v-model.trim="arrival.form.supplierName"
            placeholder="请输入供应商名称"
          />
        </el-form-item> -->

        <el-form-item label="到货数量" prop="arriveAmount">
          <el-input
            v-model.trim="arrival.form.arriveAmount"
            placeholder="请输入到货数量"
          />
        </el-form-item>

        <el-form-item label="到货时间" prop="arrivalTime">
          <el-date-picker
            v-model="arrival.form.arrivalTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择到货时间"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="arrival.loading"
          type="primary"
          @click="confirmArrivalAction"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>

    <el-dialog :visible.sync="managerApproval.isShowDialog" :title="managerApproval.title" width="400px">
      <el-form
        ref="arrivalForm"
        :model="managerApproval"
        rules="managerApproval"
        label-width="140px"
      >
        <div align="center">
          <el-button
            :loading="arrival.loading"
            type="danger"
            @click="managerApprovalDenied()"
          >审批拒绝
          </el-button>

          <el-button
            :loading="arrival.loading"
            type="success"
            @click="managerApproved()"
          >审批通过
          </el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      :visible.sync="pdfUrlShow"
      title="图纸路径"
      @close="pdfUrlShow = false"
    >
      <el-form label-width="120px">
        <el-form-item label="图纸路径：">
          <div>
            <el-button
              v-for="(url, index) in pdfUrl"
              :key="index"
              style="text-align: left;"
              type="text"
            >
              <a
                :href="url"
                style="white-space: initial; word-break: break-all; word-wrap: break-word;"
                target="_blank"
              >{{ url }}</a
              >
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="工艺：">
          <div v-for="(item, index) in artFiles" :key="index">
            <a
              :href="item"
              style="
								color: #409eff;
								border-bottom: #409eff 1px solid;
							"
              target="_blank"
            >{{ item }}</a
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :visible.sync="resubmitDataShow" title="编辑重新提交">
      <el-form
        ref="arrivalForm"
        :model="resubmitData"
        label-width="110px"
        inline
      >
        <el-form-item label="订单号" prop="orderCode">
          <el-input
            v-model.trim="resubmitData.orderCode"
            placeholder="请输入订单号"
          />
        </el-form-item>
        <el-form-item label="内部单号" prop="innerCode">
          <el-input
            v-model.trim="resubmitData.innerCode"
            placeholder="请输入内部单号"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料类型" prop="materialType">
              <el-radio-group v-model="resubmitData.materialType">
                <el-radio :label="1" disabled>产品</el-radio>
                <el-radio :label="2">材料</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              v-if="resubmitData.materialType == 2"
              label="采购类型"
              prop="purchaseType"
            >
              <el-radio-group v-model="resubmitData.purchaseType" >
                <el-radio :label="1">刀具</el-radio>
                <el-radio :label="2">物料</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="物料名称" prop="materialName">
          <el-input
            v-model.trim="resubmitData.materialName"
            placeholder="请输入物料名称"
          />
        </el-form-item>
        <el-form-item label="图号" prop="chartNo">
          <el-input
            v-model.trim="resubmitData.chartNo"
            placeholder="请输入图号"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input
            v-model.trim="resubmitData.brand"
            placeholder="请输入品牌"
          />
        </el-form-item>
        <el-form-item label="规格型号" prop="specifications">
          <el-input
            v-model.trim="resubmitData.specifications"
            placeholder="请输入规格型号"
          />
        </el-form-item>
        <el-form-item label="申请采购数量" prop="applyAmount">
          <el-input-number
            v-model="resubmitData.applyAmount"
            :min="1"
            placeholder="请输入申请采购数量"
          />
        </el-form-item>
        <el-form-item label="需求时间" prop="demandTime">
          <el-date-picker
            :picker-options="pickerOptions"
            v-model="resubmitData.demandTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input
            v-model.trim="resubmitData.unit"
            placeholder="请输入单位"
          />
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input
            v-model.trim="resubmitData.comment"
            :row="2"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="confimResubmit"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// form.demandTime.toISOString().slice(0, -5)
import user from '../../api/acl/user.js'
import { materialTypeMap, purchaseTypeMap } from '../../utils/const'
import SelectUser from '../platestoragelist/select-user.vue'

export default {
  name: 'Purchaselist',

  components: {
    SelectUser
  },

  filters: {
    getStatusLabel(row) {
      if (row.purchaseType == 1) {
        if (row.status == 1) {
          return '采购'
        }

        if (row.status == 2) {
          return '入库'
        }
      } else {
        switch (row.status) {
          case 1:
            return '采购'
            break
          case 2:
            return '品检'
            break
          case 3:
            return '入库'
            break
        }
      }
    }
  },

  props: {
    type: {
      type: String,
      default: 'purchase'
    }
  },

  data() {
    var validatePurchaseAmount = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入本次采购数量'))
      } else {
        if (value) {
          if (value > this.purchaseUpdate.row.applyAmount) {
            callback(new Error('输入的购买数量超过了申请数量！'))
          }
        }
        callback()
      }
    }

    var validatePurchasePrice = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入单价'))
      }
      callback()
    }

    var validateApplyAmount = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入申请采购数量'))
      }
      callback()
    }

    var validateDemandTime = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入时间'))
      }

      if (new Date(value).getTime() < Date.now() - 3600 * 1000 * 24) {
        callback(new Error('输入的时间不能小于当前时间'))
      }

      callback()
    }

    var validateArrivalTime = (rule, value, cb) => {
      if (!value) {
        cb(new Error('请选择到货时间'))
      }

      cb()
    }

    return {
      pdfUrl: '',
      pdfUrlShow: false,
      artFiles: [],
      orderCode: '',
      materialTypeMap,
      purchaseTypeMap,
      statusMap: {
        0: '待审核',
        1: '申请中',
        11: '待总经理审批',
        12: '待董事长审批',
        13: '总经理拒绝',
        14: '董事长拒绝',
        2: '申请完成，待到货',
        6: '到货，待品检',
        3: '品检完成',
        4: '品检完成部分',
        5: '入库完成',
        7: '已退回'
      },
      list: [],
      page: 1,
      total: 1,
      limit: 10,
      status: '',
      innerCode: '',
      innerCodeOptions: [],
      materialNameOptions: [],
      // 入库操作
      storage: {
        dialogshow: false,
        loading: false,
        row: {},
        amount: 1,
        comment: '',
        manager: '',
        tallyer: '',
        handlers: '',
        storager: sessionStorage.getItem('userName'),
        rules: {
          recordCode: [
            {
              required: true,
              message: '请输入批次号',
              trigger: 'blur'
            }
          ],
          manager: [
            {
              required: true,
              message: '请输入主管人员名称',
              trigger: 'change'
            }
          ],
          //   storager: [
          //     {
          //       required: true,
          //       message: "请输入仓库人员名称",
          //       trigger: "blur"
          //     }
          //   ],
          tallyer: [
            {
              required: true,
              message: '请输入记账人员名称',
              trigger: 'change'
            }
          ],
          handlers: [
            {
              required: true,
              message: '请输入经手人名称',
              trigger: 'change'
            }
          ],
          purchaseAmount: [
            {
              validator: validatePurchaseAmount,
              required: true,
              message: '请输入购买数量',
              trigger: 'blur'
            }
          ]
        }
      },
      // 选择需求时间
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 3600 * 1000 * 24
        }
      },
      // 采购申请
      purchaseApply: {
        dialogshow: false,
        loading: false,
        rules: {
          //   orderCode: [
          //     {
          //       required: true,
          //       message: "请输入订单号",
          //       trigger: "blur"
          //     }
          //   ],
          materialName: [
            {
              required: true,
              message: '请输入物料名称',
              trigger: 'blur'
            }
          ],
          //   chartNo: [
          //     {
          //       required: true,
          //       message: "请输入图号",
          //       trigger: "blur"
          //     }
          //   ],
          //   brand: [
          //     {
          //       required: true,
          //       message: '请输入品牌',
          //       trigger: 'blur'
          //     }
          //   ],
          //   specifications: [
          //     {
          //       required: true,
          //       message: '请输入规格型号',
          //       trigger: 'blur'
          //     }
          //   ],
          //   unit: [
          //     {
          //       required: true,
          //       message: '请输入单位',
          //       trigger: 'blur'
          //     }
          //   ],
          materialType: [
            {
              required: true,
              message: '请选择物料类型',
              trigger: 'change'
            }
          ],
          purchaseType: [
            {
              required: true,
              message: '请选择采购类型',
              trigger: 'change'
            }
          ],
          applyAmount: [
            {
              validator: validateApplyAmount,
              required: true,
              message: '请输入申请采购数量',
              trigger: 'blur'
            }
          ],
          price: [
            {
              validator: validatePurchasePrice,
              required: true,
              message: '请输入单价',
              trigger: 'blur'
            }
          ],
          demandTime: [
            {
              required: true,
              message: '请选择时间',
              trigger: 'change'
            },
            { validator: validateDemandTime, trigger: 'change' }
          ]
        },
        form: {
          orderCode: '',
          innerCode: '',
          chartNo: '',
          brand: '',
          materialName: '',
          materialType: 2,
          purchaseType: '',
          specifications: '',
          unit: '',
          applyAmount: '',
          demandTime: ''
        }
      },
      // 采购申请
      auditApply: {
        dialogshow: false,
        loading: false,
        row: {},
        rules: {},
        form: {
          id: '',
          status: 1
        }
      },
      // 采购状态更新确认
      purchaseUpdate: {
        dialogshow: false,
        loading: false,
        row: {},
        rules: {
          purchaseAmount: [
            // {
            //   validator: validatePurchaseAmount,
            //   required: true,
            //   message: "请输入购买数量",
            //   trigger: "blur"
            // }
          ],
          price: [
            {
              validator: validatePurchasePrice,
              required: true,
              message: '请输入单价',
              trigger: 'blur'
            }
          ],
          purchaseTime: [
            {
              required: true,
              message: '请选择时间',
              trigger: 'change'
            },
            { validator: validateDemandTime, trigger: 'change' }
          ]
        },
        form: {
          purchaseAmount: 1,
          qualityAmount: '',
          purchaseTime: '',
          status: '',
          comment: '',
          price: '',
          supplierName: '',
          operator:
            window.sessionStorage.getItem('userName') ||
            window.sessionStorage.getItem('fullName')
        }
      },
      // 审核
      approval: {
        visible: false,
        loading: false,
        row: {}
      },
      dialogFileUpload: {
        show: false,
        id: '',
        loading: false,
        disabled: false,
        fileName: '',
        code: '',
        formData: null,
        row: {}
      },
      excelType: ['xls', 'xlsx'],
      // 到货
      arrival: {
        show: false,
        loading: false,
        row: {},
        rules: {
          arrivalTime: [
            {
              validator: validateArrivalTime,
              required: true,
              trigger: 'blur'
            }
          ],
          supplierName: [
            {
              required: true,
              message: '请输入供应商名称',
              trigger: 'blur'
            }
          ]
        },
        form: {
          arrivalTime: '',
          supplierName: '',
          arriveAmount: '',
          operator:
            window.sessionStorage.getItem('userName') ||
            window.sessionStorage.getItem('fullName')
        }
      },
      dicPurchaseStatus: 3,
      managerApproval: {
        isShowDialog: false,
        title: '',
        id: null,
        status: null,
        purchaseAmount: null,
        price: null
      },
      resubmitData: {
        orderCode: '',
        innerCode: '',
        chartNo: '',
        brand: '',
        materialName: '',
        materialType: 2,
        purchaseType: '',
        specifications: '',
        unit: '',
        applyAmount: '',
        demandTime: '',
        status: null,
        operator: ''
      },
      resubmitDataShow: false
    }
  },

  computed: {
    // 是否是操作工
    isCl() {
      return window.sessionStorage.getItem('department') == 6
    },
    // 是否是生产主管
    isProductionStaff() {
      return window.sessionStorage.getItem('department') == 7
    },
    // 重新提交按钮权限
    isResubmitAuth() {
      return window.sessionStorage.getItem('department') != 7
    },
    // 当前界面路由是否是采购列表
    isPurchase() {
      return this.$route.path === '/purchaseList'
    },
    // 是否是仓库人员
    isPlatestorage() {
      return window.sessionStorage.getItem('department') == 10
    },
    // 是否是管理员
    isAdmin() {
      return window.sessionStorage.getItem('department') == 1
    },
    // 是否是采购人员
    isPurchaser() {
      return window.sessionStorage.getItem('department') == 11
    },
    // 是否总经理
    isGeneralManager() {
      return window.sessionStorage.getItem('department') == 1
    },
    // 是否董事长
    isChairman() {
      return window.sessionStorage.getItem('department') == 13
    },
    // 是否生产组长
    isProductionEngineer() {
      return window.sessionStorage.getItem('department') == 14
    },
    // 是否有采购申请权限
    hasApplyRole() {
      return (
        (this.isCl || this.isPlatestorage || this.isAdmin || this.isProductionEngineer) && !this.isPurchase
      )
    },
    // 是否具有查看价格的权限
    hasSeePriceRole() {
      console.log('this.isFromPurchase: ', this.isFromPurchase)
      return (
        (this.isFromPurchase && (this.isPurchaser || this.isAdmin)) ||
        (this.isFromPlatestorage && (this.isPlatestorage || this.isAdmin))
      )
    },
    // 是否是生产界面
    isFromManufacturing() {
      return this.$route.path === '/manufacturing/purchaseList'
    },
    // 来自仓库界面的饮用
    isFromPlatestorage() {
      return (
        this.$route.path === '/platestoragelist' && this.type === 'platestorage'
      )
    },
    // 来自生产界面的饮用
    isFromPurchase() {
      return this.$route.path === '/purchaseList'
      //   return this.type === "purchase";
    }
  },

  watch: {
    'purchaseUpdate.row': {
      deep: true,
      handler(row) {
        this.purchaseUpdate.form.price = row.price
      }
    }
  },

  created() {
    this.getList()
  },

  methods: {
    valChangeHandlers(val) {
      console.log(val)
      this.storage.handlers = val
    },
    valChangeTallyer(val) {
      console.log(val)
      this.storage.tallyer = val
    },
    valChangeManager(val) {
      console.log(val)
      this.storage.manager = val
    },
    seePaper(row) {
      user.listImageFolder(row).then(response => {
        if (response && response.imageUrl) {
          this.pdfUrl =
            typeof response.imageUrl === 'string'
              ? [response.imageUrl]
              : response.imageUrl || []
          this.pdfUrlShow = true
          this.artFiles = response.artFiles
        } else {
          this.$message.info('暂无图纸信息')
        }
      })
    },
    beforeUploadFile(file) {
      const { excelType } = this
      const fileName = file.name
        .substring(file.name.lastIndexOf('.') + 1)
        .toLowerCase()

      // 验证excel类型
      if (!excelType.includes(fileName)) {
        this.$message({
          message: `上传文件只能是 ${excelType.join('、')}格式!`,
          type: 'warning'
        })
        return false
      }

      const formData = new FormData()
      formData.append('file', file)

      this.dialogFileUpload.fileName = file.name
      this.dialogFileUpload.formData = formData
    },
    closeUploadFileDialog() {
      this.dialogFileUpload.fileName = ''
      this.dialogFileUpload.formData = null
      this.dialogFileUpload.show = false
      this.getList()
    },
    removeFile() {
      this.dialogFileUpload.fileName = ''
      this.dialogFileUpload.formData = null
    },
    confirmUpload() {
      const {
        dialogFileUpload: { fileName, formData }
      } = this
      if (!fileName || !formData) return false

      this.dialogFileUpload.loading = true

      const uploadPromise = user.purchaseApplyImport(formData)

      uploadPromise.then(res => {
        this.dialogFileUpload.loading = false
        this.dialogFileUpload.disabled = true
        this.$message.success(res.message || '导入成功')
        this.closeUploadFileDialog()
      })
    },
    selectStatus(val) {
      this.status = val
      this.getList()
    },
    selected() {
      this.getList()
    },
    fetchData(val) {
      this.page = val
      this.getList()
    },
    getList() {
      const query = {
        page: this.page,
        limit: this.limit,
        status: this.status,
        orderCode: this.innerCode
      }

      user.purchaseList(query).then(response => {
        this.total = response.total
        this.list = response.list
      })
    },
    // 采购操作
    purchaseUpdateAction(row) {
      this.purchaseUpdate.row = row
      this.purchaseUpdate.dialogshow = true
    },
    applyTurnDown(val) {
      const data = {
        id: val.id,
        status: 7
      }
      this.$confirm('确定要驳回改采购申请吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          user
            .purchaseApplyUpdate(data)
            .then(res => {
              this.$message({
                message: '驳回成功',
                type: 'success'
              })
              this.getList()
            })
        })
    },
    // 确认采购
    confirmPurchaseUpdateAction() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const { row, form } = this.purchaseUpdate
          const data = {
            id: row.id,
            purchaseAmount: form.purchaseAmount,
            purchaseTime: form.purchaseTime,
            status: 2,
            comment: form.comment,
            supplierName: form.supplierName,
            price: form.price,
            operator: form.operator
          }
          let generalManager = null
          let chairman = null
          user.commonListDict(this.dicPurchaseStatus).then(response => {
            response.forEach(item => {
              if (item.id === 46) {
                generalManager = item.code * 10000
              }
              if (item.id === 47) {
                chairman = item.code * 10000
              }
            })
            const totalAccount = data.purchaseAmount * data.price
            console.log('总金额：{}', totalAccount)
            console.log('总金额：{}', generalManager)
            if (totalAccount >= generalManager) {
              data.status = 11
            }
            user
              .purchaseApplyUpdate(data)
              .then(res => {
                this.$refs.form.resetFields()
                this.purchaseUpdate.loading = false
                this.purchaseUpdate.dialogshow = false
                this.purchaseUpdate.form.qualityAmount = 1
                this.getList()
              })
              .catch(err => {
                this.purchaseUpdate.loading = false
              })
            this.purchaseUpdate.loading = true
          })
        }
      })
    },
    arrivalAction(row) {
      this.arrival.row = row
      this.arrival.show = true
    },
    confirmArrivalAction() {
      const { row, form } = this.arrival
      const data = {
        id: row.id,
        status: row.purchaseType == 2 ? 6 : 3,
        arrivalTime: form.arrivalTime
          ? form.arrivalTime
          : '',
        // supplierName: form.supplierName,
        arriveAmount: form.arriveAmount,
        operator: form.operator
      }

      this.$refs.arrivalForm.validate(valid => {
        if (valid) {
          this.arrival.loading = true

          user
            .purchaseApplyUpdate(data)
            .then(res => {
              this.$message.success('操作成功')
              this.$refs.arrivalForm.resetFields()
              this.arrival.loading = false
              this.arrival.show = false
              this.getList()
            })
            .catch(err => {
              this.arrival.loading = false
            })
        }
      })
    },
    getStatus() {
      const {
        storage: { row, amount }
      } = this

      if (row.status == 1) {
        return 2
      }

      if (row.purchaseType == 1) {
        if (row.status == 2) {
          return 5
        }
      } else {
        if (row.status == 2 && amount == row.applyAmount) {
          return 3
        }

        if (row.status == 2 && amount < row.applyAmount) {
          return 4
        }

        if (row.status == 3) {
          return 5
        }
      }
    },
    // 入库
    storageAction(row) {
      this.storage.row = row
      this.storage.amount =
        row.purchaseType == 1
          ? row.purchaseAmount - row.realAmount
          : row.currentQualityAmount
      this.storage.materialType = row.materialType
      this.storage.purchaseType = row.purchaseType
      this.storage.dialogshow = true
    },
    // 审核
    auditAction(row) {
      this.auditApply.row = row
      this.auditApply.dialogshow = true
    },
    // 确认入库
    confirmStorage() {
      this.$refs.storageForm.validate(valid => {
        if (valid) {
          const {
            storage: {
              row,
              amount,
              materialType,
              purchaseType,
              comment,
              supplierName,
              manager = '',
              tallyer = '',
              handlers = '',
              storager = ''
            }
          } = this
          const status = this.getStatus()

          this.storage.loading = true

          const data = {
            applyId: row.id, // 采购申请id
            recordCode: row.orderCode,
            manager, // 主管人员名称
            tallyer, // 记账人员名称
            handlers, // 经手人名称
            storager, // 仓库人员名称
            innerCode: row.innerCode, // 内部单号
            chartNo: row.chartNo, // 图号
            brand: row.brand, // 品牌
            materialName: row.materialName, // 物料名称
            materialType,
            purchaseType,
            specifications: row.specifications, // 规格型号
            unit: row.unit, // 单位
            price: row.price, // 价格
            comment: comment, // 备注
            supplierName: supplierName,
            operator: window.sessionStorage.getItem('userName'), // 操作者
            amount, // 数量
            status
          }

          user
            .storagePurchasePut(data)
            .then(res => {
              this.$message({
                message: '入库成功',
                type: 'success'
              })
              this.storage.amount = 1
              this.$refs.storageForm.resetFields()
              this.storage.loading = false
              this.storage.dialogshow = false
              this.getList()
            })
            .catch(() => {
              this.storage.loading = false
            })
        } else {
          return false
        }
      })
    },
    // 确认采购申请
    confirmPurchaseApply() {
      this.$refs.applyform.validate(valid => {
        if (valid) {
          const { form } = this.purchaseApply
          const operator = window.sessionStorage.getItem('userName')
          this.purchaseApply.loading = true

          if (form.materialType == 1) delete form.purchaseType

          const {
            isPlatestorage,
            isCl,
            isFromPlatestorage,
            isFromPurchase,
            isAdmin
          } = this
          // 操作工提交的采购申请需要审核，仓库模块提交的采购申请不需要审核
          if ((isPlatestorage || isAdmin) && isFromPlatestorage) {
            form.status = 1
          }
          // 操作工申请的，状态初始化为待审核
          // 0的话就是要审批的，审批完改成1
          if ((isCl || isAdmin) && isFromPurchase) {
            form.status = 0
          }

          Object.assign(form, {
            creator: operator,
            operator
          })

          console.log('form: ', form)

          user
            .purchaseApply(
              Object.assign({}, form, {
                demandTime: form.demandTime
              })
            )
            .then(res => {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.$refs.applyform.resetFields()
              this.purchaseApply.form.applyAmount = 1
              this.purchaseApply.loading = false
              this.purchaseApply.dialogshow = false
              this.getList()
            })
            .catch(err => {
              this.purchaseApply.loading = false
            })
        } else {
          return false
        }
      })
    },
    // 审批
    approvalAction(row) {
      this.approval.row = row
      this.approval.visible = true
    },
    confimResubmit() {
      this.resubmitData.status = 0
      this.resubmitData.operator = window.sessionStorage.getItem('userName')

      this.$confirm('你确定重新提交吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          user.editPurchase(this.resubmitData).then(res => {
            this.$message({
              message: '重新申请成功',
              type: 'success'
            })
            this.getList()
            this.resubmitDataShow = false
          })
        })
    },
    resubmit(row) {
      this.resubmitDataShow = true
      user.getPurchaseDetail(row.id).then(res => {
        this.resubmitData = res
      })
    },
    // 驳回申请
    turnDownAction(row) {
      const { id } = row
      const data = {
        id,
        status: 7,
        operator: window.sessionStorage.getItem('userName') // 操作者
      }
      console.log('data----->: ', data)
      this.$confirm('确定要驳回改申请记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          user.purchaseApplyUpdate(data).then(res => {
            this.$message({
              message: '驳回成功',
              type: 'success'
            })
            this.getList()
          })
        })
    },
    // 确认审批
    confirmApproval() {
      this.approval.loading = true
      const { id } = this.approval.row

      const data = {
        id,
        status: 1,
        operator: window.sessionStorage.getItem('userName') // 操作者
      }
      console.log('data----->: ', data)

      user.purchaseApplyUpdate(data).then(res => {
        this.$message({
          message: '审核成功',
          type: 'success'
        })
        this.closeApprovalDialog()
        this.getList()
      })
    },
    // 关闭审批提示
    closeApprovalDialog() {
      this.approval.visible = false
      this.approval.loading = false
    },
    remoteInnerCode(query) {
      if (query !== '') {
        user
          .getOrderCode(query)
          .then(response => {
            this.innerCodeOptions = response
            debugger
          })
      } else {
        this.innerCodeOptions = []
      }
    },
    remoteMaterialName(query) {
      if (query !== '' && this.purchaseApply.form.innerCode !== '') {
        user
          .getProductImportByOrder(query, this.purchaseApply.form.innerCode)
          .then(response => {
            this.materialNameOptions = response
          })
      } else {
        this.materialNameOptions = []
      }
    },
    // 确认审核通过
    confirmAudit() {
      this.$refs.auditApplyForm.validate(valid => {
        const operator = window.sessionStorage.getItem('userName')
        this.auditApply.loading = true

        const {
          auditApply: { row }
        } = this

        const data = {
          id: row.id, // 采购申请id
          status: 1,
          operator: operator
        }

        user
          .purchaseApplyUpdate(data)
          .then(res => {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.$refs.auditApplyForm.resetFields()
            this.auditApply.loading = false
            this.auditApply.dialogshow = false
            this.getList()
          })
          .catch(err => {
            this.auditApply.loading = false
          })
      })
    },
    managerApprovalMethod(val) {
      if (val.status === 11) {
        this.managerApproval = {
          isShowDialog: true,
          title: '总经理审批',
          id: val.id,
          status: val.status,
          purchaseAmount: val.purchaseAmount,
          price: val.price
        }
      }
      if (val.status === 12) {
        this.managerApproval = {
          isShowDialog: true,
          title: '董事长审批',
          id: val.id,
          status: val.status,
          purchaseAmount: val.purchaseAmount,
          price: val.price
        }
      }
    },
    managerApprovalDenied() {
      if (this.managerApproval.status === 11) {
        this.managerApproval.status = 13
      }
      if (this.managerApproval.status === 12) {
        this.managerApproval.status = 14
      }
      user
        .purchaseApplyUpdate(this.managerApproval)
        .then(res => {
          this.managerApproval = {
            isShowDialog: false,
            title: '',
            id: null,
            status: null
          }
          this.getList()
        })
    },
    managerApproved() {
      if (this.managerApproval.status === 11) {
        debugger
        let generalManager = null
        let chairman = null
        user.commonListDict(this.dicPurchaseStatus).then(response => {
          response.map(item => {
            if (item.id === 46) {
              generalManager = item.code * 10000
            }
            if (item.id === 47) {
              chairman = item.code * 10000
            }
          })
        })
        const totalAccount = this.managerApproval.purchaseAmount * this.managerApproval.price
        console.log('2222222', totalAccount)
        debugger
        if (totalAccount >= chairman) {
          this.managerApproval.status = 12
        } else {
          this.managerApproval.status = 2
        }
        user
          .purchaseApplyUpdate(this.managerApproval)
          .then(res => {
            this.managerApproval = {
              isShowDialog: false,
              title: '',
              id: null,
              status: null
            }
            this.getList()
          })
      } else {
        this.managerApproval.status = 2
        user
          .purchaseApplyUpdate(this.managerApproval)
          .then(res => {
            this.managerApproval = {
              isShowDialog: false,
              title: '',
              id: null,
              status: null
            }
            this.getList()
          })
      }
    }
  }
}
</script>

<style>
.establish {
  text-align: right;
  padding-bottom: 20px;
}
</style>
